#ifndef CONFIG_CENTER5_ITEM_ARRAY_T_20110412
#define CONFIG_CENTER5_ITEM_ARRAY_T_20110412

#include <assert.h>
#include <iostream>

template<class ItemType>
class ItemArrayT
{
public:
    typedef ItemType Item_T;

    ItemArrayT() : m_bInit(false), m_pArray(NULL), m_dwSize(0)
    {
    }
    ~ItemArrayT()
    {
    }

    int Initialize(char* pBuf, uint32_t dwLen, uint32_t dwBlockNum)
    {
        assert(pBuf);
        assert(dwLen > 0);

        if (dwBlockNum * sizeof(Item_T) > dwLen)
        {
            return -1;
        }

        m_pArray = reinterpret_cast<Item_T*>(pBuf);
        m_dwSize = dwBlockNum;

        m_bInit = true;

        return 0;
    }
    
    Item_T& operator[] (uint32_t dwIndex)
    {
        //printf("Item_array:: dwIndex:%d, m_dwSize:%d\n", dwIndex, m_dwSize);
        assert(m_bInit);
        assert(dwIndex >= 0 && dwIndex < m_dwSize);
    
        return *(m_pArray + dwIndex);
    }
    
    uint32_t GetSize() const
    {
        assert(m_bInit);
        
        return m_dwSize;
    }   
    
    void* GetBuf() const
    {
        assert(m_bInit);
    
        return reinterpret_cast<void*>(m_pArray);
    }

    void Dump(std::ostream& os, uint32_t dwMaxSize = 0)
    {
        assert(m_bInit);
    
        if (dwMaxSize > m_dwSize)
        {
            dwMaxSize = m_dwSize;
        }
    
        for (uint32_t i = 0; i < dwMaxSize; i++)
        {
            Item_T& rItem = *(m_pArray + i);
            os << "[" << i << "] " << rItem;
        }
    }

private:
    bool m_bInit;
    Item_T* m_pArray;
    uint32_t m_dwSize;
};

#endif //CONFIG_CENTER5_ITEM_ARRAY_T_20110412

